<template>
  <div class="training-detail-container">
    <div class="top">
      <span class="course-title">所学课程：{{ showTrainingDetail.name }}</span>
      <div
        style="
          display: flex;
          justify-content: space-between;
          align-items: flex-end;
        "
      >
        <div class="top_1">
          <span>课程时长：{{ (showTrainingDetail.duration / 60).toFixed(1) }}小时</span>
          <span>课程数量：{{ getCourseCount() }}</span>
          <span>开始时间：{{ formatStartTime }}</span>
          <span>结束时间：{{ formatEndTime }}</span>
        </div>
        <img :src="showTrainingDetail.cover" class="cover-image" />
      </div>
    </div>

    <div class="bottom">
      <van-tabs v-model:active="activeTab" @change="clickHandler">
        <van-tab
          v-for="(item, index) in tabItems"
          :key="index"
          :title="item"
        ></van-tab>
      </van-tabs>

      <div class="bottom-content-training">
        <!-- 描述内容 -->
        <div class="description-content" v-if="activeTab === 0">
          {{ showTrainingDetail.description }}
        </div>

        <!-- 课程内容 -->
        <div v-if="activeTab === 1">
          <van-cell-group inset v-if="pptList.length > 0">
            <van-cell
              v-for="(item, index) in pptList"
              :key="item.id"
              :title="`${index + 1}. ${item.name}`"
              @click="pptClickHandler(item)"
              is-link
            >
              <template #icon>
                <van-icon name="description" class="cell-icon" />
              </template>
            </van-cell>
          </van-cell-group>

          <van-cell-group
            inset
            v-if="wordList.length > 0"
            style="margin-top: 10px"
          >
            <van-cell
              v-for="(item, index) in wordList"
              :key="item.id"
              :title="`${pptList.length + index + 1}. ${item.name}`"
              @click="wordClickHandler(item)"
              is-link
            >
              <template #icon>
                <van-icon name="records" class="cell-icon" />
              </template>
            </van-cell>
          </van-cell-group>

          <van-cell-group
            inset
            v-if="videoList.length > 0"
            style="margin-top: 10px"
          >
            <van-cell
              v-for="(item, index) in videoList"
              :key="item.id"
              :title="`${pptList.length + wordList.length + index + 1}. ${
                item.name
              }`"
              @click="videoClickHandler(item)"
              is-link
            >
              <template #icon>
                <van-icon name="play-circle-o" class="cell-icon" />
              </template>
              <template #right-icon>
                <div class="video-progress">
                  <div class="duration-tag">
                    {{ getDuration(item.duration) }}
                  </div>
                  <div
                    class="progress-text"
                    v-if="getVideoProgress(item.url) > 0"
                  >
                    已学习 {{ getVideoProgress(item.url) }}%
                  </div>
                </div>
              </template>
            </van-cell>
          </van-cell-group>
        </div>

        <!-- 试卷内容 -->
        <div class="exam-content" v-if="activeTab === 2">
          <div class="exam-info">
            <span>试卷标题：{{ props.showTrainingDetail.name }}课后试卷</span>
            <span
              >试卷数量：{{
                Math.ceil(props.showTrainingDetail.duration / 12)
              }}</span
            >
            <span>合格分数：{{ props.showTrainingDetail.passed_score }}</span>
            <span>最高分数：{{ maxScore }}</span>
            <span>考试次数：{{ props.showTrainingDetail.can_test_count }}</span>
            <span>剩余次数：{{ remainingCount }}</span>
          </div>

          <div class="exam-status">
            <div
              v-if="maxScore >= props.showTrainingDetail.passed_score"
              class="exam-passed"
            >
              <van-icon name="success" size="50" color="#67c23a" />
              <div class="status-text">考试通过</div>
            </div>
            <van-button
              v-else-if="remainingCount > 0"
              icon="clock-o"
              type="primary"
              block
              @click="startExam"
              >开始考试</van-button
            >
            <div v-else class="exam-failed">
              <van-icon name="cross" size="50" color="#ee0a24" />
              <div class="status-text">考试未通过</div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, watch, computed } from "vue";
import { useRouter } from "vue-router";
import testApi from "@/api/subject/test";
import store from "@/store";
import { showNotify } from "vant";

const router = useRouter();
// 定义组件属性
const props = defineProps({
  showTrainingDetail: {
    type: Object,
    required: true, // 添加必填属性
    default: () => ({}), // 添加默认值
  },
});

// 添加标签页数据和激活状态
const tabItems = computed(() => {
  const baseItems = ["描述", "课程"];
  return props.showTrainingDetail.need_test === 1
    ? [...baseItems, "试卷"]
    : baseItems;
});
const activeTab = ref(0);
const pptList = ref([]);
const videoList = ref([]);
const wordList = ref([]);
const remainingCount = ref(0);
const maxScore = ref(0);

const updateRemainCount = async () => {
  try {
    const res = await testApi.getTestedCountAndScore(
      props.showTrainingDetail.id
    );
    remainingCount.value =
      props.showTrainingDetail.can_test_count - res.data.testedCount;
    maxScore.value = res.data.maxScore;
  } catch (err) {
    remainingCount.value = 0;
  }
};

// 监听 activeTab 变化，当切换到试卷标签时更新剩余次数
watch(activeTab, (newVal) => {
  if (newVal === 2) {
    updateRemainCount();
  }
});

onMounted(() => {
  if (activeTab.value === 1) {
    loadCourseData();
  }
  if (activeTab.value === 2) {
    updateRemainCount();
  }
});

const videoClickHandler = (data) => {
  // 打开一个新的页面，页面路由时/training/video
  router.push({
    path: "/video",
    query: {
      url: data.url,
      id: props.showTrainingDetail.id,
      name: props.showTrainingDetail.name,
    },
  });
};

const startExam = () => {
  if (store.getters.name) {
    if (flag) {
      testApi
        .startExam(
          props.showTrainingDetail.id,
          Math.ceil(props.showTrainingDetail.duration / 12),
          store.getters.name,
          props.showTrainingDetail.name
        )
        .then((res) => {
          router.push({
            path: "/trainingexam",
            query: {
              type: "subjectTest",
              questionItemId: res.data,
              name: props.showTrainingDetail.name,
            },
          });
        });
    } else {
      showNotify({
        type: "danger",
        message: "请学完全部课程！",
        duration: 1500,
      });
    }
  }
};

const wordClickHandler = (data) => {
  router.push({
    path: "/file",
    query: {
      file: data.url,
      name: data.name,
    },
  });
};

const pptClickHandler = (data) => {
  //这个iframeSrc的页面改成从springboot中获取
  router.push({
    path: "/file",
    query: {
      file: data.url,
      name: data.name,
    },
  });
};

const getDuration = (duration) => {
  const hours = Math.floor(duration / 3600);
  const minutes = Math.floor((duration % 3600) / 60);
  const seconds = duration % 60;

  let result = "";
  if (hours > 0) {
    result += `${hours}小时`;
  }
  if (minutes > 0) {
    result += `${minutes}分`;
  }
  result += `${seconds}秒`;
  return result;
};

const clickHandler = (index) => {
  activeTab.value = index;
  switch (index) {
    case 0:
      break;
    case 1:
      loadCourseData();
      break;
    case 2:
      //检查视频是否都已经播放完毕
      const arr = JSON.parse(props.showTrainingDetail.video_info);
      for (let index = 0; index < arr.length; index++) {
        const element = arr[index];
        const url = element.url;
        if (getVideoProgress(url) < 100) {
          flag = false;
          break;
        }
      }
      break;
  }
};

let flag = true;
const getCourseCount = () => {
  if (props.showTrainingDetail.id) {
    const length1 = props.showTrainingDetail.ppt_info
      ? JSON.parse(props.showTrainingDetail.ppt_info).length
      : 0;
    const length2 = props.showTrainingDetail.video_info
      ? JSON.parse(props.showTrainingDetail.video_info).length
      : 0;
    const length3 = props.showTrainingDetail.word_info
      ? JSON.parse(props.showTrainingDetail.word_info).length
      : 0;
    return length1 + length2 + length3;
  }
  return 0;
};

const getVideoProgress = (fileName) => {
  const progress = localStorage.getItem(
    `video-progress-${fileName}-${props.showTrainingDetail.id}`
  );
  return progress ? Math.floor(parseFloat(progress) * 100) : 0;
};

const formatStartTime = computed(() => {
  return props.showTrainingDetail.start_time?.split("T")[0] || "";
});

const formatEndTime = computed(() => {
  return props.showTrainingDetail.end_time?.split("T")[0] || "";
});

// Add a new function to load course data
const loadCourseData = () => {
  try {
    pptList.value = props.showTrainingDetail.ppt_info
      ? JSON.parse(props.showTrainingDetail.ppt_info)
      : [];
    videoList.value = props.showTrainingDetail.video_info
      ? JSON.parse(props.showTrainingDetail.video_info)
      : [];
    wordList.value = props.showTrainingDetail.word_info
      ? JSON.parse(props.showTrainingDetail.word_info)
      : [];
    console.log("PPT list length:", pptList.value.length);
    console.log("Video list length:", videoList.value.length);
    console.log("Word list length:", wordList.value.length);
  } catch (error) {
    console.error("Error parsing course data:", error);
    pptList.value = [];
    videoList.value = [];
    wordList.value = [];
  }
};
</script>

<style scoped>
.training-detail-container {
  margin-top: -20px;
  width: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.top {
  background-color: white;
  width: 100%;
  border-radius: 8px;
  border: 1px solid #ebedf0;
  display: flex;
  flex-direction: column;
  padding: 10px;
}

.top_1 {
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.course-title {
  display: block;
  font-size: 16px;
  font-weight: bold;
  color: #333;
  margin-bottom: 5px;
}

.cover-image {
  width: 30%;
  height: auto;
  max-height: 150px;
  object-fit: contain;
}

.bottom {
  width: 105%;
  margin-top: 5px;
  background-color: white;
  border-radius: 8px;
  border: 1px solid #ebedf0;
  overflow: hidden;
}

.bottom-content-training {
  padding: 5px;
  padding-bottom: 25px;
}

.description-content {
  line-height: 1.6;
  color: #333;
}

.cell-icon {
  margin-right: 5px;
}

.video-progress {
  display: flex;
  align-items: center;
  gap: 8px;
}

.duration-tag {
  padding: 2px 8px;
  background-color: #67c23a;
  border-radius: 12px;
  color: white;
  font-size: 12px;
}

.progress-text {
  color: #67c23a;
  font-size: 12px;
  white-space: nowrap;
}

.exam-content {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.exam-info {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.exam-status {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.exam-passed,
.exam-failed {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 10px;
}

.status-text {
  font-size: 16px;
  font-weight: bold;
}

/* 媒体查询适配大屏设备 */
@media screen and (min-width: 768px) {
  .top {
    flex-direction: row;
    justify-content: space-between;
    align-items: center;
    padding: 15px;
  }

  .cover-image {
    width: auto;
    height: 130px;
    margin-top: 0;
  }

  .exam-content {
    flex-direction: row;
    justify-content: space-between;
    align-items: center;
  }

  .exam-info {
    width: 60%;
  }

  .exam-status {
    width: 35%;
    margin-top: 0;
  }
}
</style>
